<template>
	<view class="content">
		<!-- 聊天内容 -->
		<scroll-view class="chat" :style="{'height':emoji||plus?'calc(100vh - 260px)':'calc(100vh - 60px)'}"
			scroll-y="true" :scroll-into-view="scrollToView">
			<view class="chat-main">
				<view class="chat-ls" v-for="(item,index) in messageList" :key="index" v-if="item.type != 7">
					<view class="chat-time" v-if="item.createTime != ''">{{changeTime(item.createTime)}}
					</view>
					<!-- 左侧消息 -->
					<view class="msg-m msg-left" v-if="item.toId ==  fromUserId">
						<image class="user-img" :src="friendImage" @click="goToFriendDetail"></image>
						<view class="message" v-if="item.msgType == 611">
							<!-- 文字 -->
							<view class="msg-text">{{item.message}}</view>
						</view>
						<view class="message" v-if="item.msgType == 4">
							<!-- 图像 -->
							<image :src="item.message" class="msg-img" mode="widthFix"
								@click="previewImg(item.message)"></image>
						</view>
						<view class="message" v-if="item.msgType == 5&&roomId!=item.message" @click="goToVedio">
							<!-- 文字 -->
							<view class="msg-text">[视频通话]</view>
						</view>

						<view class="message" v-if="item.msgType == 5&&roomId==item.message" @click="goToAnswerVedio">
							<!-- 文字 -->
							<view class="msg-text">[点击接听视频通话]</view>
						</view>

						<view class="message" v-if="item.msgType == 6&&roomId!=item.message" @click="goToVoice">
							<!-- 文字 -->
							<view class="msg-text">[语音通话]</view>
						</view>

						<view class="message" v-if="item.msgType == 6&&roomId==item.message" @click="goToAnswerVoice">
							<!-- 文字 -->
							<view class="msg-text">[点击接听语音通话]</view>
						</view>

					</view>

					<!-- 右侧消息 -->
					<view class="msg-m msg-right" v-if="item.toId != fromUserId">
						<image class="user-img" :src="image"></image>
						<!-- 文字 -->
						<view class="message" v-if="item.msgType == 611">
							<view class="msg-text">{{item.message}}</view>
						</view>
						<!-- 图像 -->
						<view class="message" v-if="item.msgType == 4">
							<image :src="item.message" class="msg-img" mode="widthFix"
								@click="previewImg(item.message)"></image>
						</view>
						<view class="message" v-if="item.msgType == 5" @click="goToVedio">
							<!-- 文字 -->
							<view class="msg-text">[视频通话]</view>
						</view>

						<view class="message" v-if="item.msgType == 6" @click="goToVoice">
							<!-- 文字 -->
							<view class="msg-text">[语音通话]</view>
						</view>

					</view>
					<view :id="'msg'+ index"> </view>
				</view>
			</view>
		</scroll-view>
		<view class="bottom" :style="{'height':emoji||plus?'260px':'60px'}">
			<!-- 输入框 -->
			<view class="newMessage">
				<input type="input" :value="content" @input="changeInput" @focus="close">

				<image src="../../../static/emoji-c.png" v-if="emoji" @click="emojiClose" mode="aspectFit"
					style="width: 35px;height: 35px;">
				</image>
				<image src="../../../static/emoji.png" v-else @click="emojiOpen" mode="aspectFit"
					style="width: 35px;height: 35px;">
				</image>

				<view class="send" v-if="content!=''" @click="sendMessage(611)">发送</view>
				<image src="../../../static/plus-c.png" v-else-if="plus" @click="plusClose" mode="aspectFit"
					style="width: 35px;height: 35px;">
				</image>
				<image src="../../../static/plus.png" v-else @click="plusOpen" mode="aspectFit"
					style="width: 35px;height: 35px;">
				</image>

			</view>
			<!-- 表情弹出框 -->
			<view class="popup" v-if="emoji">
				<view class="emoji" v-for="(item,index) in emojiList" :key="index" @click="chooseEmoji(item)">
					{{item}}
				</view>
			</view>

			<!-- 功能弹出框 -->
			<view class="popup" v-if="plus">
				<image src="../../../static/image.png" @click="goToImage" mode="aspectFit"></image>
				<image src="../../../static/camera.png" @click="goToCamera" mode="aspectFit"></image>
				<image src="../../../static/phone.png" @click="goToVoice" mode="aspectFit"></image>
				<image src="../../../static/vedio.png" @click="goToVedio" mode="aspectFit"></image>

			</view>
		</view>

	</view>
</template>

<script>
	import dateTime from '../../../utils/dateTime.js';
	import {
		socket
	} from '../../../utils/socket.js';
	import DB from 'utils/sqlite.js';
	export default {
		data() {
			return {
				token: "",
				fromUserId: uni.getStorageSync("userId"),
				image: "",
				toUserId: "",
				friendName: "",
				friendImage: "",
				scrollToView: "",
				content: "",
				emoji: false,
				plus: false,
				send: false,
				emojiList: ["😄", "😆", "😊", "😃", "😏", "😍",
					"😘", "😚", "😳", "😌", "😆", "😁",
					"😉", "😜", "😝", "😀", "😗", "😙",
					"😛", "😴", "😟", "😦", "😧", "😮",
					"😬", "😕", "😯", "😑", "😒", "😅",
					"😓", "😥", "😩", "😔", "😞", "😖",
					"😨", "😰", "😣", "😢", "😭", "😂",
					"😲", "😱", "😫", "😠", "😡", "😤",
					"😪", "😋", "😷", "😎", "😵", "👿",
					"😈", "😐", "😶", "😇", "👽"
				],
				messageList: [],
				roomId: ""
			}
		},
		methods: {
			previewImg(photoImg) {
				let imgsArray = [];
				imgsArray[0] = photoImg;
				uni.previewImage({
					current: 0,
					urls: imgsArray
				});
			},
			goToFriendDetail() {

			},
			changeTime(date) {
				return dateTime.dateTime1(date);
			},
			// 滚动到底部
			goBottom() {
				console.log('msg' + (this.messageList.length - 1));
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.messageList.length - 1)
				})
			},
			// 打开表情弹出框
			emojiOpen() {
				this.emoji = true
				this.plus = false
				this.goBottom()
			},
			// 打开功能弹出框
			plusOpen() {
				this.plus = true
				this.emoji = false
				this.goBottom()
			},
			// 关闭表情弹出框
			emojiClose() {
				this.emoji = false
			},
			// 关闭功能弹出框
			plusClose() {
				this.plus = false
			},
			// 表情和功能全关闭
			close() {
				this.emojiClose()
				this.plusClose()
			},
			changeInput(e) {
				this.content = e.detail.value
				console.log(e.detail.value)
			},
			// 选择表情
			chooseEmoji(e) {
				this.content = this.content + e
				console.log(this.content)
			},
			//选择图片
			goToImage() {
				let that = this;
				uni.chooseImage({
					sourceType: ['album'], //从相册选择
					success(res) {
						console.log(res);
						for (var i = 0; i < res.tempFilePaths.length; i++) {
							let filePath = res.tempFilePaths[i]

							uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: Math.floor(Math.random() * 900000000) + 100000000 + '.jpg',
								success(res) {
									that.content = res.fileID;
									that.sendMessage(4)
								}
							});
						}
					}
				});
			},
			//进入相机
			goToCamera() {
				let that = this;
				uni.chooseImage({
					sourceType: ['camera'], //从相册选择
					count: 1,
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						uniCloud.uploadFile({
							filePath: res.tempFilePaths[0],
							cloudPath: Math.floor(Math.random() * 900000000) + 100000000 + '.jpg',
							success(res) {
								that.content = res.fileID;
								that.sendMessage(1)
							}
						});
					}
				})
			},
			//进入语音通话
			goToVoice() {

			},
			goToAnswerVoice() {

			},
			//进入视频通话
			goToVedio() {
				uni.navigateTo({
					url:"/pages/contact/vedio/vedio?type=to&fromId="+this.fromUserId+"&toId="+this.toUserId
				})
			},
			goToAnswerVedio() {

			},
			getMsgList() {
				let open = DB.isOpen();
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					DB.selectTableDataOr("chatRecords_" + uni.getStorageSync("userId"), "fromId", this.toUserId, "toId", this.toUserId)
						.then(res => {
							console.log("chatRecords表数据", res);
							this.messageList = res;
							setTimeout(() => {
								this.goBottom();
							}, 100);
						})
						.catch(error => {
							console.log("chatRecords表数据查询失败", error);
						});
				} else {
					this.showToast("数据库未打开");
				}
			},
			sendMessage(type) {
				var message = {
					type: 1,
					fromId: this.fromUserId,
					toId: Number(this.toUserId),
					msgType: type,
					message: this.content,
					createTime: Date.now()
				}

				socket.send(JSON.stringify(message))
				console.log(message);
				this.insertIntoSql(message);

				this.messageList.push(message)
				this.content = ""
				this.goBottom()
			},
			insertIntoSql(record) {
				let chatRecordsSql =
					`'${record.type}','${record.fromId}','${record.toId}','${record.msgType}','${record.message}','${record.createTime}'`;
				let chatRecordsCondition = "'type','fromId','toId','msgType','message','createTime'";

				DB.insertTableData("chatRecords_" + uni.getStorageSync("userId"), chatRecordsSql, chatRecordsCondition)
					.then(res => {
						console.log("chatRecords新增数据成功");
					})
					.catch(error => {
						console.log("chatRecords新增数据失败", error);
					});

				let chatListSql =
					`'${record.toId}','${record.type}','${record.msgType}','${record.message}','${record.createTime}'`;
				let chatListCondition = "'id','type','msgType','lastMessage','createTime'";
				DB.insertOrReplaceData("chatList_" + uni.getStorageSync("userId"), chatListSql,chatListCondition)
					.then(res => {
						console.log("chatList新增数据成功");
					})
					.catch(error => {
						console.log("chatList新增数据失败", error);
					});
			},
			clearUnReadCount() {
				uni.setStorageSync("unReadCount" + this.toUserId, 0);
			},
		},
		onLoad(e) {
			this.toUserId = e.userId;
			this.friendName = e.userName;
			this.image = getApp().url +  "image/userId-" + uni.getStorageSync("userId") + ".png";
			const map = new Map(Object.entries(JSON.parse(uni.getStorageSync("friendImage"))));
			this.friendImage = map.get(e.userId);
			this.getMsgList();
			socket.getMessage(res => {
				if (JSON.parse(res.data).fromId == this.toUserId) {
					console.log(res);
					this.messageList.push(JSON.parse(res.data));
					this.goBottom();
				}

			})
		},
		onReady() {
			// 更改标题为好友姓名
			uni.setNavigationBarTitle({
				title: this.friendName
			})
		},
		onUnload() {
			this.clearUnReadCount();
		}
	}
</script>

<style lang="scss">
	page {
		height: 100vh;
	}

	.content {
		height: 100vh;
		background-color: #EDEDED;
	}

	.chat {
		height: calc(100vh - 60px);

		.chat-main {
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-top: 20rpx;
			display: flex;
			flex-direction: column;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 10rpx 0rpx;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
				}

				.message {
					flex: none;
					max-width: 480rpx;
				}

				.msg-text {
					font-size: 32rpx;
					color: rgba(39, 40, 50, 1);
					line-height: 44rpx;
					padding: 18rpx 24rpx;
					word-break: break-all;
					user-select: text
				}

				.msg-img {
					max-width: 400rpx;
					border-radius: 20rpx;
				}
			}

			.msg-left {
				flex-direction: row;

				.msg-text {
					margin-left: 16rpx;
					background-color: #fff;
					border-radius: 0rpx 20rpx 20rpx 20rpx;
				}

				.msg-img {
					margin-left: 16rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;

				.msg-text {
					margin-right: 16rpx;
					background-color: #41A863;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
					color: #fff;
				}

				.msg-img {
					margin-right: 16rpx;
				}
			}
		}
	}

	.bottom {
		height: 60px;

		.newMessage {
			height: 60px;
			width: 100vw;
			background-color: #F6F6F6;
			display: flex;
			justify-content: space-around;
			align-items: center;


			input {
				background-color: #fff;
				width: 70vw;
				height: 40px;
				border-radius: 10px;
			}

			.send {
				width: 60px;
				height: 35px;
				color: #fff;
				text-align: center;
				line-height: 35px;
				border-radius: 10px;
				background-color: #41A863;
			}


		}

		.popup {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			padding: 10px 2vw;
			height: 180px;

			.emoji {
				width: 12.5%;
				padding: 1vw auto;
				text-align: center;
			}

			image {
				width: 11%;
				height: 15vw;
				margin: 1vw 7%;
			}
		}
	}
</style>